# configuration for this webapp

import os, Queue, socket
import yaki.Engine, yaki.Store, yaki.Cache
from yaki.Utils import *
from yaki.Indexer import *
from yaki.Plugins import *
from yaki.Tracker import *
from yaki.Feeds import *

name="Yaki"
docroot="web"
hashroot = os.path.join(os.environ.get('HOME','/'),'tmp/%s' % name)
defaultRequestEncoding = defaultOutputEncoding = "utf-8"
sessionTimeoutSecs=1800
snakelets= {
  "space"      : yaki.Engine.Wiki,             # The main Wiki snakelet
  "feeds"      : yaki.Feeds.RSS,               # The RSS snakelet
  "track"      : yaki.Tracker.Referrals,       # Referral Tracker (uses client-side JavaScript)
  "media"      : yaki.Engine.Attachment,       # The file attachment server
  "del.icio.us": yaki.Engine.DeliciousImporter # The link blog importer
}

configItems = {
  # The site info (for meta tags, RSS, etc.)
  # the siteurl is used to build absolute URLs
  "siteinfo": {'sitetitle': 'Yaki', # page titles
               'sitename': 'Yaki Wiki Engine', # for site banner, RSS feeds
               'sitedescription': 'Powered by Python. Dipped in BeautifulSoup. Flavored with Snakelets.',
               # set this to override URL generation when using a reverse proxy
               #'siteurl':'http://domainname' 
               # set this to ping services (currently technorati) upon updates
               # 'ping' : {'technorati':'http://ping_url'}
  },
  # Machine names and local pathnames for deployment.
  # staging: True disables full text indexing
  # store: None defaults to ROOT/space
  "deployment": { 
     "sample":    {"store": None, "staging": False }
  },
  # Locale used for all localizable strings
  "locale": "en_US",
  # The base URLs for Wiki pages and media, used for URL generation
  "base": "/space/",
  "media": "/media/",
  # Special page prefixes we use in lieu of namespaces
  "namespaces": ['meta','dev','tests','docs','blog','people','links','podcast'],
  # default author - you really, really want to change this...
  "author": "Rui Carmo",
  # default markup - only used if nothing else is specified.
  "markup": "text/x-textile",
  # del.icio.us feed for linkblog - comment to disable
  "del.icio.us": "http://del.icio.us/rss/tag/snakelets+yaki",
  # maximum age for HTTP and disk caching
  "maxage": 3600,
  # time frame for enabling comments (blog namespace only, disabled if zero)
  "commentwindow": 15 * 86400,
  # Note: Haloscan username is inserted directly into theme template
  # standing redirects for legacy/alternate pathnames
  "redirects" : { # standing redirects
    '^blog\/(\d+)-(\d+)$' : 'blog/\\1/\\2',
    '^blog\/(\d+)-(\d+)-(\d+)$' : 'blog/\\1/\\2/\\3',
    '^blog\/(\d+)-(\d+)-(\d+).(\d+):(\d+)$' : 'blog/\\1/\\2/\\3/\\4\\5',
    '^Applications\/(.+)$' : 'apps/\\1',
    '^RecentChanges$' : 'meta/RecentChanges',
    '^Referrers$' : 'meta/Referrers'
  },
  # page and feed templates
  'templates' : { 
    # Generic item template
    'generic': u"""
    <div class="hentry p1 post publish alt">
  	  <div class="entry-head">
  	    <h1 class="entry-title"><a href="%(permalink)s" class="%(linkclass)s" rel="bookmark" title="%(description)s">%(posttitle)s</a></h1>
  	    <small class="entry-meta"><span class="chronodata">%(postinfo)s</span></small>
  	  </div> <!-- .entry-head -->
      <div class="entry-content">
        %(content)s
      </div> <!-- .entry-content -->
      <div class="comments">
      %(comments)s
      </div>
    </div> <!-- #post-ID -->
    """, 
    # linkblog item template
    'linkblog': u"""
    <div class="hentry p1 post publish alt">
      <div class="entry-head">
        <h4 class="entry-title"><a rel="bookmark" class="%(linkclass)s" title="%(description)s" href="%(link)s">%(posttitle)s</a>&nbsp;<a class="wikilink" title="permalink to this entry" href="%(permalink)s"><img class="permalink-bullet" src="/img/bullet_blue.png" alt="permalink"/></a></h4>
  	    <small class="entry-meta"><span class="chronodata">%(tags)s</span></small>
  	  </div> <!-- .entry-head -->
      <div class="entry-content">
        %(content)s
      </div> <!-- .entry-content -->
    </div> <!-- #post-ID -->
    """,
    # Simplified item
    'simplified': u"""
    <div class="hentry p1 post publish alt">
     <div class="entry-content">
        %(content)s
      </div> <!-- .entry-content -->
      <div class="comments">
      %(comments)s
      </div>
    </div> <!-- #post-ID -->
    """,
    # Comments (enabled)
    'comments-enabled' : u"""
    <a href="javascript:HaloScan('%(page)s');" target="_self">
    <script type="text/javascript">postCount('%(page)s');</script> enabled for %(window)s days</a> |
    <a href="javascript:HaloScanTB('%(page)s');" target="_self">
    <script type="text/javascript">postCountTB('%(page)s');</script></a> | 
    <a href="http://digg.com/submit?phase=2&url=%(permalink)s&title=%(title)s">digg this</a> |
    <a href="http://del.icio.us/post?url=%(permalink)s&title=%(title)s">del.icio.us</a>
    """,
    # Comments (disabled)
    'comments-disabled' : u"""
    Comments have been automatically disabled |
    <a href="http://digg.com/submit?phase=2&url=%(permalink)s&title=%(title)s">digg this</a> |
    <a href="http://del.icio.us/post?url=%(permalink)s&title=%(title)s">del.icio.us</a>
    """,
    # RSS Feed
    'rss-feed' : u"""<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
    <channel>
    	<title>%(sitetitle)s</title>
    	<link>%(siteurl)s</link>
    	<description>%(sitedescription)s</description>
        <copyright>CC Attribution-NonCommercial-NoDerivs 3.0</copyright>
        <ttl>30</ttl>
    	<pubDate>%(pubdate)s</pubDate>
    	<lastBuildDate>%(builddate)s</lastBuildDate>
      <docs>http://blogs.law.harvard.edu/tech/rss</docs>
      <generator>yaki</generator>
    	%(items)s
    </channel>
    </rss>
    """,
    # RSS Item
    'rss-item' : u"""
    <item>
       <title>%(title)s</title>
       <link>%(link)s</link>
       <description>%(description)s&lt;br/&gt;&lt;small&gt;&lt;a href="%(link)s" title="link to %(link)s"&gt;@&lt;/a&gt;&lt;/small&gt;</description>
       <pubDate>%(pubdate)s</pubDate>
       <author>%(author)s</author>
       <source url="%(siteurl)s">%(sitetitle)s</source>
       <category>%(category)s</category>
       <guid isPermalink="false">%(guid)s</guid>
    </item>
    """
  }
}

	
def init(webapp):
  print ">> INIT WEBAPP",webapp
  home = os.environ.get("HOME","")
  c = webapp.getContext()
  c.base = webapp.getConfigItem('base')
  c.cache = yaki.Cache.Cache(hashroot + '/cache')
  c.commentwindow = webapp.getConfigItem('commentwindow')
  c.defaultmarkup = webapp.getConfigItem('markup')
  c.locale = webapp.getConfigItem('locale')
  c.media = webapp.getConfigItem('media')
  c.namespaces = webapp.getConfigItem('namespaces')
  c.persistent = yaki.Cache.Cache(hashroot + '/persistent')
  c.redirects = webapp.getConfigItem('redirects')
  c.siteinfo = webapp.getConfigItem('siteinfo')
  c.templates = webapp.getConfigItem('templates')
  print ">> INITIALIZING STORE"
  deployment = webapp.getConfigItem('deployment')
  root = os.path.join(webapp.getFileSystemPath(),'space')
  staging = False
  for hostname in deployment.keys():
    if re.match("^%s" % hostname, socket.gethostname()):
      root = deployment[hostname]['store']
      staging = deployment[hostname]['staging']
  c.store = yaki.Store.Store(root)
  print ">> INITIALIZING INDEX"
  if staging == True:
    print "INFO: Staging mode. full text indexing is disabled."
  c.indexer = Indexer(c, hashroot + '/index', c.store, c.cache, staging)
  c.indexer.start()
  print ">> INITIALIZING PLUGINS"
  c.plugins = PluginRegistry(webapp, 'plugins')
  print ">> DONE INIT WEBAPP",webapp

def close(webapp):
  print ">> CLOSE WEBAPP",webapp
  c = webapp.getContext()
  c.indexer.stop()
  print ">> DONE CLOSE WEBAPP",webapp
